# api/services.py

from passlib.context import CryptContext
from datetime import datetime, timedelta
import jwt
from sqlalchemy.orm import Session
from api.models import User  # 导入 User 模型
import bcrypt

# 创建密码上下文
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

def hash_password(password: str) -> str:
    """加密密码"""
    return pwd_context.hash(password)

def verify_password(plain_password: str, hashed_password: str) -> bool:
    """验证密码"""
    return pwd_context.verify(plain_password, hashed_password)

def create_user(db: Session, user_data: dict):
    """
    创建新用户
    """
    # 加密密码
    hashed_password = hash_password(user_data["password"])
    db_user = User(
        username=user_data["username"],
        password=user_data["password"],
        hashed_password=hashed_password,
        email=user_data.get("email"),
        created_at=datetime.now(),
    )
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return {
        "username": db_user.username,
        "email": db_user.email,
    }

def authenticate_user(db: Session, username: str, password: str):
    """
    验证用户登录
    """
    user = db.query(User).filter(User.username == username).first()
    if not user:
        return None  # 用户不存在
    if not verify_password(password, user.hashed_password):
        return None  # 密码错误
    return user

SECRET_KEY = "mini_my_tool_back"  # 替换为您的密钥
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 60*24*30

def create_access_token(data: dict):
    """
    生成 JWT Token
    """
    to_encode = data.copy()
    expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    to_encode.update({"exp": expire})
    encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
    return encoded_jwt

def decode_access_token(token: str):
    """
    解码 JWT Token，获取用户信息
    """
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        return payload
    except jwt.PyJWTError:
        return None